package dd.server;

import java.util.ArrayList;

import server.ClientState;
import server.IProtocolHandler;
import server.Server;
import xml.Message;
import dd.model.Edge;
import dd.model.Event;
import dd.model.serverModel;

public class signInResponseController implements IProtocolHandler {

	public Message process(ClientState client, Message request) {
		String eventId = request.contents.getFirstChild().getAttributes().getNamedItem("id").getNodeValue();

		Message message = null;
		String xmlString = null;
		boolean validClient = false;

		// add a new user under this event
		Event event = serverModel.getInstance().getEventByEventId(eventId);

		if (event == null) { // decide if this is a valid event
			xmlString = Message.responseHeader(request.id(),
					"Sorry, the Event ID you inputed is invalid, please check with your moderator!")
					+ "<signInResponse id='"
					+ eventId
					+ "' behavior='mock' type='mock' question='' numChoices='0' numRounds='0' position='0'>"
					+ "<choice value='mock' index='0'/>" + "</signInResponse></response>";
		} else { // decide if this event meets the maximum of player
			validClient = true;

			int maxClientsCount = event.getNumberLines();
			int currentClientsCount = serverModel.getInstance().getClientIdsByEventId(eventId).size();

			if (maxClientsCount > currentClientsCount) {
				// add this new client and allow to attend this event
				serverModel.getInstance().getClientIdsByEventId(eventId).add(client.id());

				String numberofline = String.valueOf(event.getNumberLines());
				String numberofedge = String.valueOf(event.getNumberEdges());

				xmlString = Message.responseHeader(request.id()) + "<signInResponse id='" + eventId + "' behavior='"
						+ event.getType() + "' type='" + event.getMode() + "' question='" + event.getEventName()
						+ "' numChoices='" + numberofline + "' numRounds='" + numberofedge + "' position='1'>"
						+ "<choice value='" + event.getChoice(0) + "' index='0'/>" + "<choice value='"
						+ event.getChoice(1) + "' index='1'/>" + "<choice value='" + event.getChoice(2)
						+ "' index='2'/>" + "<choice value='" + event.getChoice(3) + "' index='3'/>"
						+ "</signInResponse></response>";
			} else {
				xmlString = Message.responseHeader(request.id(),
						"Sorry, this Event meets the maximum clients, you cannot attend this event!")
						+ "<signInResponse id='"
						+ eventId
						+ "' behavior='mock' type='mock' question='' numChoices='0' numRounds='0' position='0'>"
						+ "<choice value='mock' index='0'/>" + "</signInResponse></response>";
			}
		}
		message = new Message(xmlString);
		// valid clien to open the "addEdgeFrame" window, allow to generate duplicated windows but discard the second
		// one...
		if (validClient) {
			// 1, send to the client to open the addEdgeFrame window
			if (Server.ids().contains(client.id())) {
				Server.getState(client.id()).sendMessage(message);
			}
			// 2, send to the client the existing edge list (TODO: allow duplicated edge)
			ArrayList<Edge> edges = event.getedgelist();
			if (edges == null || edges.size() == 0) {
				// don't send
			} else {
				String innerString = null;
				for (Edge edge : edges) {
					innerString = Message.responseHeader(request.id()) + "<addEdgeResponse id='" + eventId + "' left='"
							+ edge.getleft() + "' right='" + edge.getright() + "' height='" + edge.getheight() + "'>"
							+ "</addEdgeResponse></response>";
					// send this response to all the client
					if (Server.ids().contains(client.id())) {
						Server.getState(client.id()).sendMessage(new Message(innerString));
					} else {
						break;
					}
				}
			}
		}
		// Event e = sm.getEvent();
		// Event e = new Event();
		// Node update = request.contents.getFirstChild();
		// NamedNodeMap map = request.contents.getFirstChild().getAttributes();
		// String geteventid = map.getNamedItem("id").getNodeValue();
		// System.out.println("receivedid:" + geteventid);
		// String numberofline = String.valueOf(event.getNumberLines());
		// String numberofedge = String.valueOf(event.getNumberEdges());

		// Construct message reflecting state
		/*
		 * String xmlString = Message.responseHeader(request.id()) +
		 * "<signInResponse id='"+geteventid+"' behavior='"+e.getType()+"' type='"
		 * +e.getMode()+"' question='"+e.getEventName()+"' numChoices='"
		 * +e.getNumberLines()+"' numRounds='"+e.getNumberEdges()+"' position='2'>"+
		 * 
		 * "</signInResponse></response>";
		 */
		// String xmlString = Message.responseHeader(request.id()) + "<signInResponse id='" + eventId + "' behavior='"
		// + event.getType() + "' type='" + event.getMode() + "' question='" + event.getEventName()
		// + "' numChoices='" + numberofline + "' numRounds='" + numberofedge + "' position='1'>"
		// + "<choice value='" + event.getChoice(0) + "' index='0'/>" + "<choice value='" + event.getChoice(1)
		// + "' index='1'/>" + "<choice value='" + event.getChoice(2) + "' index='2'/>" + "<choice value='"
		// + event.getChoice(3) + "' index='3'/>" + "</signInResponse></response>";
		// record this id to server id for event 135
		// int i;
		// i = sm.getnumofuserin();
		// sm.setuserid(i, request.id());
		// sm.setnumofuserin(i + 1);
		// send this response back to the client which sent us the request.
		return message;
	}
}
